package com.cqu.hospitalsystem.service.impl;

import com.cqu.hospitalsystem.service.FileService;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StreamUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.util.Base64;

@Service("FileService")
public class FileServiceImpl implements FileService {

    private final String constUrl = "D:\\0\\winterProject\\file";

    @Override
    public ResponseEntity<byte[]> getImg(String img_addr) {
        try {
            if (img_addr == null || img_addr.equals("")) {
                img_addr = "null.png";
            }
            File file = new File(this.constUrl + File.separator + "img" + File.separator + img_addr);
            if (!file.exists()) {
                return ResponseEntity.notFound().build();
            }
            InputStream inputStream = new FileInputStream(file);
            byte[] bytes = StreamUtils.copyToByteArray(inputStream);
            String contentType = "image/png"; // 这里应该根据文件的实际类型来设置
            return ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType(contentType))
                    .body(bytes);
        } catch (IOException e) {
            System.err.println("IO异常: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.internalServerError().body(null);
        }
    }

    @Override
    public ResponseEntity<String> getImgBase64(String img_addr) {
        try {
            if (img_addr == null || img_addr.equals("")) {
                img_addr = "null.png";
            }
            File file = new File(this.constUrl + File.separator + "img" + File.separator + img_addr);
            if (!file.exists()) {
                return ResponseEntity.notFound().build();
            }
            // 读取文件为字节数组
            byte[] bytes = Files.readAllBytes(file.toPath());
            // 编码为base64
            String base64Encoded = Base64.getEncoder().encodeToString(bytes);
            // 这里应该根据文件的实际类型来设置
            String contentType = "image/png";
            // 构建base64字符串，包含数据类型
            String base64String = base64Encoded;
            return ResponseEntity.ok().body(base64String);
        } catch (IOException e) {
            System.err.println("IO异常: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.internalServerError().body(null);
        }
    }
}
